package com.mantou.mantouaiagent.config.springsecurity;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.mantou.mantouaiagent.entities.SpringSecurityUserDetails;
import com.mantou.mantouaiagent.util.ThreadLocalUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**登录认证过滤器
 * @auther zzyy
 * @create 2024-12-22 17:52
 */

@Component
@Slf4j
public class LoginAuthenticationFilter extends OncePerRequestFilter
{
    @Value("${jwt.secret}")
    private String jwtSecret;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException
    {
            // 1.从http请求头里面获取 JWT 令牌，请查看自己定义的ajaxutil.js里面的headers叫什么名字，请保持两者一致
            String token = request.getHeader("Authorization");
        log.info("Request Path: {}", request.getRequestURL()); // 添加路径日志

//            System.out.println("------>"+token);


            // 2.JWT令牌不为空
            if(!StrUtil.hasEmpty(token))
            {
                // 3.token不为空验证JWT令牌正确性
                if (JWTUtil.verify(token, jwtSecret.getBytes()))
                {
                    // 4.获取用户信息存储到SpringSecurity中
                    JWT jwt = JWTUtil.parseToken(token);
                    if (jwt != null && jwt.getPayload("uid") != null)
                    {
                        Integer uid = Integer.parseInt(jwt.getPayload("uid").toString());
                        ThreadLocalUtil.setUserId(uid);
                        String username = (String) jwt.getPayload("username");
                        //5 创建SpringSecurity用户对象,需要自己实现UserDetails接口并新建
                        SpringSecurityUserDetails userDetails = new SpringSecurityUserDetails(uid, username, "");

                        UsernamePasswordAuthenticationToken authentication =
                                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                        SecurityContextHolder.getContext().setAuthentication(authentication);
                        log.info("登录用户：{}", SecurityContextHolder.getContext().getAuthentication());
                    }
                }
            }else {
                String method = request.getRequestURI();
                log.info(method+":执行非登录操作");
            }
            filterChain.doFilter(request, response);
    }
}


